// Carlito — the little agent character.
// A round ember/firefly orb with eyes, antennae, and tiny limbs.
// Grows from a tiny spark to a confident superintelligent agent across the strip.

function Carlito({
  x = 0, y = 0,
  size = 60,
  stage = 1,                    // 1..6 — narrative growth
  expression = 'curious',       // curious | determined | thinking | joyful | wise | confident
  glow = true,
  rotate = 0,
  bobble = 0,                   // applied y bobble for breathing
  cape = false,                 // for final hero stage
  scale = 1,
}) {
  // Color shift across the journey: ember → spark → cyan → firefly → moonlight gold
  const palette = {
    1: { core: '#FFC089', mid: '#FF6B35', edge: '#8C2A0F', eye: '#0A0A0A' }, // tiny spark
    2: { core: '#FFD089', mid: '#FF8B45', edge: '#8C2A0F', eye: '#0A0A0A' }, // grounds
    3: { core: '#C7FCFF', mid: '#00F0FF', edge: '#0E5A6B', eye: '#0A0A0A' }, // lab cyan
    4: { core: '#FFE89A', mid: '#FFB23A', edge: '#7A3A0F', eye: '#0A0A0A' }, // campfire warm
    5: { core: '#D4FFD8', mid: '#7FFF00', edge: '#3A6B0E', eye: '#0A0A0A' }, // cabin firefly
    6: { core: '#FFF1A6', mid: '#F2A93B', edge: '#8C5A1A', eye: '#0A0A0A' }, // hero gold-ember
  }[Math.max(1, Math.min(6, stage))];

  // Eye shapes per expression
  const eyes = {
    curious:    { lx: 0.32, rx: 0.62, ly: 0.42, ry: 0.42, w: 0.10, h: 0.14, brow: 0 },
    determined: { lx: 0.32, rx: 0.62, ly: 0.44, ry: 0.44, w: 0.10, h: 0.06, brow: 1 },
    thinking:   { lx: 0.32, rx: 0.62, ly: 0.44, ry: 0.44, w: 0.10, h: 0.10, brow: 0.5 },
    joyful:     { lx: 0.32, rx: 0.62, ly: 0.44, ry: 0.44, w: 0.10, h: 0.04, brow: 0 },
    wise:       { lx: 0.32, rx: 0.62, ly: 0.44, ry: 0.44, w: 0.10, h: 0.08, brow: 0 },
    confident:  { lx: 0.32, rx: 0.62, ly: 0.42, ry: 0.42, w: 0.10, h: 0.08, brow: 0.7 },
  }[expression];

  const w = size * scale;
  return (
    <div style={{
      position: 'absolute',
      left: x, top: y,
      width: w, height: w,
      transform: `translate(-50%, -50%) translateY(${bobble}px) rotate(${rotate}deg)`,
      filter: glow ? `drop-shadow(0 0 ${w*0.25}px ${palette.mid}aa) drop-shadow(0 0 ${w*0.6}px ${palette.mid}55)` : 'none',
      pointerEvents: 'none',
    }}>
      <svg viewBox="0 0 100 100" width={w} height={w} style={{ overflow: 'visible' }}>
        {/* Cape (hero stage) */}
        {cape && (
          <path
            d="M 22 50 Q 8 70 18 92 Q 30 78 30 60 Z M 78 50 Q 92 70 82 92 Q 70 78 70 60 Z"
            fill="#C72C2C"
            stroke="#0A0A0A"
            strokeWidth="2"
          />
        )}

        {/* Antenna */}
        <line x1="50" y1="14" x2="50" y2="2" stroke="#0A0A0A" strokeWidth="2.5" strokeLinecap="round"/>
        <circle cx="50" cy="2" r="3.5" fill={palette.core} stroke="#0A0A0A" strokeWidth="1.5"/>

        {/* Body — gradient sphere */}
        <defs>
          <radialGradient id={`grad-${stage}-${expression}`} cx="35%" cy="32%">
            <stop offset="0%" stopColor={palette.core}/>
            <stop offset="55%" stopColor={palette.mid}/>
            <stop offset="100%" stopColor={palette.edge}/>
          </radialGradient>
        </defs>
        <circle cx="50" cy="52" r="34" fill={`url(#grad-${stage}-${expression})`} stroke="#0A0A0A" strokeWidth="3"/>

        {/* Specular highlight */}
        <ellipse cx="38" cy="38" rx="8" ry="5" fill="rgba(255,255,255,0.5)"/>

        {/* Eyebrows */}
        {eyes.brow > 0 && (
          <>
            <path d={`M ${eyes.lx*100 - 6} ${eyes.ly*100 - 8 + (1-eyes.brow)*4} L ${eyes.lx*100 + 6} ${eyes.ly*100 - 10}`}
                  stroke="#0A0A0A" strokeWidth="2.5" strokeLinecap="round" fill="none"/>
            <path d={`M ${eyes.rx*100 - 6} ${eyes.ry*100 - 10} L ${eyes.rx*100 + 6} ${eyes.ry*100 - 8 + (1-eyes.brow)*4}`}
                  stroke="#0A0A0A" strokeWidth="2.5" strokeLinecap="round" fill="none"/>
          </>
        )}

        {/* Eyes */}
        <ellipse cx={eyes.lx*100} cy={eyes.ly*100} rx={eyes.w*100} ry={eyes.h*100} fill={palette.eye}/>
        <ellipse cx={eyes.rx*100} cy={eyes.ry*100} rx={eyes.w*100} ry={eyes.h*100} fill={palette.eye}/>
        {/* Eye sparkles */}
        {expression !== 'determined' && expression !== 'joyful' && (
          <>
            <circle cx={eyes.lx*100 + 2} cy={eyes.ly*100 - 2} r="1.5" fill="#FFFFFF"/>
            <circle cx={eyes.rx*100 + 2} cy={eyes.ry*100 - 2} r="1.5" fill="#FFFFFF"/>
          </>
        )}

        {/* Mouth */}
        {expression === 'joyful' && (
          <path d="M 38 64 Q 50 76 62 64" stroke="#0A0A0A" strokeWidth="2.5" fill="none" strokeLinecap="round"/>
        )}
        {expression === 'curious' && (
          <ellipse cx="50" cy="66" rx="3" ry="2" fill="#0A0A0A"/>
        )}
        {expression === 'determined' && (
          <line x1="42" y1="66" x2="58" y2="66" stroke="#0A0A0A" strokeWidth="2.5" strokeLinecap="round"/>
        )}
        {expression === 'thinking' && (
          <path d="M 42 66 Q 50 64 58 67" stroke="#0A0A0A" strokeWidth="2.5" fill="none" strokeLinecap="round"/>
        )}
        {expression === 'wise' && (
          <path d="M 42 66 Q 50 70 58 66" stroke="#0A0A0A" strokeWidth="2.5" fill="none" strokeLinecap="round"/>
        )}
        {expression === 'confident' && (
          <path d="M 40 64 Q 50 72 60 64" stroke="#0A0A0A" strokeWidth="2.5" fill="none" strokeLinecap="round"/>
        )}

        {/* Tiny arms — appear at stage 2+ */}
        {stage >= 2 && (
          <>
            <path d="M 18 56 Q 10 60 8 68" stroke="#0A0A0A" strokeWidth="3" fill="none" strokeLinecap="round"/>
            <path d="M 82 56 Q 90 60 92 68" stroke="#0A0A0A" strokeWidth="3" fill="none" strokeLinecap="round"/>
            {/* Hand dots */}
            <circle cx="8" cy="68" r="3.5" fill={palette.mid} stroke="#0A0A0A" strokeWidth="1.5"/>
            <circle cx="92" cy="68" r="3.5" fill={palette.mid} stroke="#0A0A0A" strokeWidth="1.5"/>
          </>
        )}

        {/* Tiny legs — stage 3+ */}
        {stage >= 3 && (
          <>
            <line x1="38" y1="86" x2="36" y2="96" stroke="#0A0A0A" strokeWidth="3" strokeLinecap="round"/>
            <line x1="62" y1="86" x2="64" y2="96" stroke="#0A0A0A" strokeWidth="3" strokeLinecap="round"/>
            <ellipse cx="35" cy="97" rx="4" ry="2" fill="#0A0A0A"/>
            <ellipse cx="65" cy="97" rx="4" ry="2" fill="#0A0A0A"/>
          </>
        )}

        {/* Scout patch — stage 4+ */}
        {stage >= 4 && (
          <g transform="translate(70 65)">
            <circle r="9" fill="#F5EBD8" stroke="#0A0A0A" strokeWidth="2"/>
            <text x="0" y="3" textAnchor="middle" fontFamily="Akira Expanded, sans-serif" fontSize="9" fontWeight="800" fill="#C72C2C">★</text>
          </g>
        )}
      </svg>
    </div>
  );
}

// Action lines (radial speed lines) for emphasis
function ActionLines({ x, y, count = 14, length = 60, color = '#0A0A0A', opacity = 1, rotate = 0 }) {
  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      transform: `translate(-50%,-50%) rotate(${rotate}deg)`,
      opacity, pointerEvents: 'none',
    }}>
      <svg width={length*2} height={length*2} viewBox={`-${length} -${length} ${length*2} ${length*2}`} style={{overflow:'visible'}}>
        {Array.from({ length: count }).map((_, i) => {
          const a = (i/count) * Math.PI * 2;
          const r1 = length * 0.55;
          const r2 = length * (0.85 + 0.15 * ((i*7)%5)/5);
          return (
            <line
              key={i}
              x1={Math.cos(a)*r1} y1={Math.sin(a)*r1}
              x2={Math.cos(a)*r2} y2={Math.sin(a)*r2}
              stroke={color} strokeWidth="3" strokeLinecap="round"
            />
          );
        })}
      </svg>
    </div>
  );
}

// Onomatopoeia sticker — for SNAP! BOOM! ZAP! POW!
function Onomatopoeia({ x, y, text, color = '#FF6B35', size = 64, rotate = -6, progress = 0, ease = 'pop' }) {
  // pop-in scale curve
  const t = Math.max(0, Math.min(1, progress));
  const popScale =
    t < 0.18 ? t / 0.18 * 1.3 :
    t < 0.32 ? 1.3 - (t - 0.18) / 0.14 * 0.3 :
    1.0;
  const opacity = t < 0.05 ? t / 0.05 : (t > 0.92 ? (1 - t) / 0.08 : 1);

  return (
    <div style={{
      position: 'absolute', left: x, top: y,
      transform: `translate(-50%,-50%) rotate(${rotate}deg) scale(${popScale})`,
      opacity,
      fontFamily: 'Akira Expanded, "Cocogoose Pro", sans-serif',
      fontWeight: 900,
      fontSize: size,
      letterSpacing: '0.02em',
      color: color,
      WebkitTextStroke: '3px #0A0A0A',
      textShadow: `5px 5px 0 #0A0A0A`,
      pointerEvents: 'none',
      whiteSpace: 'nowrap',
    }}>
      {text}
    </div>
  );
}

// Comic-style speech bubble
function ComicBubble({ x, y, w = 200, text, tail = 'bl', rotate = -2, bg = '#F5EBD8', fontSize = 18, font, progress = 1, anchor = 'center' }) {
  const t = Math.max(0, Math.min(1, progress));
  const scale = t < 0.3 ? (t / 0.3) * 1.05 : (t < 0.45 ? 1.05 - (t-0.3)/0.15*0.05 : 1);
  const opacity = t < 0.15 ? t / 0.15 : 1;

  // anchor: 'center' → x,y is bubble center; 'tail' → x,y is the tail tip
  const tailOffsets = {
    bl: { x: -w*0.35, y:  40 },
    br: { x:  w*0.35, y:  40 },
    tl: { x: -w*0.35, y: -40 },
    tr: { x:  w*0.35, y: -40 },
  }[tail] || { x: 0, y: 0 };

  const cx = anchor === 'tail' ? x - tailOffsets.x : x;
  const cy = anchor === 'tail' ? y - tailOffsets.y : y;

  return (
    <div style={{
      position: 'absolute', left: cx, top: cy,
      transform: `translate(-50%,-50%) rotate(${rotate}deg) scale(${scale})`,
      opacity,
      pointerEvents: 'none',
    }}>
      <div style={{
        background: bg,
        border: '3px solid #0A0A0A',
        borderRadius: 16,
        padding: '12px 16px',
        boxShadow: '4px 4px 0 #0A0A0A',
        minWidth: w,
        maxWidth: w * 1.2,
        position: 'relative',
        textAlign: 'center',
      }}>
        <div style={{
          fontFamily: font || 'Nirakolu, "Project Note", system-ui, sans-serif',
          fontSize, fontWeight: 800,
          color: '#0A0F0A',
          lineHeight: 1.15,
          letterSpacing: '0.01em',
        }}>{text}</div>
        {/* tail */}
        <svg style={{
          position: 'absolute',
          left: tail.includes('l') ? '20%' : '60%',
          [tail.includes('t') ? 'bottom' : 'top']: '100%',
          transform: tail.includes('t') ? 'rotate(180deg)' : 'none',
          width: 30, height: 24,
          overflow: 'visible',
        }}>
          <polygon points="0,0 24,0 8,22" fill={bg} stroke="#0A0A0A" strokeWidth="3" strokeLinejoin="round"/>
          <polygon points="2,-2 22,-2 8,20" fill={bg}/>
        </svg>
      </div>
    </div>
  );
}

Object.assign(window, { Carlito, ActionLines, Onomatopoeia, ComicBubble });
