// Battery / Power Source visual component

const Battery = ({
  source,
  draw,
  onChange,
  onDelete,
  onPortMouseDown,
  onCardMouseDown,
  onCardMouseMove,
  selected,
  pendingTarget,
  period
}) => {
  const { id, name, amount, x, y } = source;
  const remaining = amount - draw;
  const pct = amount > 0 ? Math.max(0, Math.min(1, remaining / amount)) : 0;
  const overload = draw > amount && amount > 0;
  const empty = amount > 0 && pct < 0.001;

  const fillColor = overload ? 'var(--red)' :
                    pct < 0.15 ? 'var(--amber)' :
                    pct < 0.4 ? 'var(--green)' : 'var(--cyan)';
  const fillDim = overload ? 'var(--red-dim)' :
                  pct < 0.15 ? 'var(--amber-dim)' :
                  pct < 0.4 ? 'var(--green-dim)' : 'var(--cyan-dim)';

  // Heartbeat pulse: power sources pulse when carrying load. Faster when overloaded, slower when idle.
  const isLive = draw > 0 && amount > 0;
  const pulseClass = !isLive ? '' :
                     overload ? 'pulse-red' :
                     pct < 0.15 ? 'pulse-amber' :
                     pct < 0.4 ? 'pulse-green' :
                     'pulse-cyan';

  // 8 cells in the battery
  const cells = 8;
  const filledCells = Math.round(pct * cells);

  const periodSuffix = period === 'monthly' ? '/mo' : period === 'biweekly' ? '/2wk' : '/wk';

  return (
    <div
      className={`battery-card ${pulseClass}`}
      style={{
        position: 'absolute',
        left: x,
        top: y,
        width: 240,
        transformOrigin: 'center center',
        background: 'linear-gradient(180deg, var(--bg-2), var(--bg-1))',
        border: `1px solid ${selected ? 'var(--cyan)' : 'var(--line-2)'}`,
        borderRadius: 14,
        padding: '14px 14px 18px',
        ...(pulseClass ? {} : {
          boxShadow: selected
            ? '0 0 0 3px rgba(76, 243, 255, 0.15), 0 8px 32px rgba(0,0,0,0.6)'
            : '0 8px 24px rgba(0,0,0,0.5), inset 0 1px 0 rgba(255,255,255,0.03)',
        }),
        cursor: 'grab',
        userSelect: 'none',
        transition: 'border-color 0.15s'
      }}
      onMouseDown={(e) => onCardMouseDown(e, id, 'source')}
      onTouchStart={(e) => onCardMouseDown(e, id, 'source')}
    >
      {/* status strip */}
      <div style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginBottom: 10,
        fontFamily: 'JetBrains Mono, monospace',
        fontSize: 9,
        letterSpacing: '0.15em',
        color: 'var(--ink-2)',
        textTransform: 'uppercase'
      }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
          <span style={{
            width: 6, height: 6, borderRadius: '50%',
            background: overload ? 'var(--red)' : empty ? 'var(--amber)' : 'var(--green)',
            boxShadow: `0 0 8px ${overload ? 'var(--red)' : empty ? 'var(--amber)' : 'var(--green)'}`,
            animation: 'pulse-glow 1.6s infinite'
          }} />
          PWR-{String(id).slice(-3).toUpperCase()}
        </span>
        <button
          onClick={(e) => { e.stopPropagation(); onDelete(id); }}
          onMouseDown={(e) => e.stopPropagation()}
          style={{
            background: 'transparent',
            border: 'none',
            color: 'var(--ink-3)',
            fontSize: 11,
            padding: 2,
            opacity: 0.5
          }}
          onMouseEnter={(e) => e.currentTarget.style.color = 'var(--red)'}
          onMouseLeave={(e) => e.currentTarget.style.color = 'var(--ink-3)'}
        >✕</button>
      </div>

      {/* name + bolt icon row */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
        <svg
          width="18" height="18" viewBox="0 0 20 20" fill="none"
          className={overload ? 'bolt-hum-fast' : isLive ? 'bolt-hum' : 'bolt-idle'}
          style={{
            color: overload ? 'var(--red)'
                  : pct < 0.15 ? 'var(--amber)'
                  : pct < 0.4 ? 'var(--green)'
                  : 'var(--cyan)',
            flexShrink: 0,
            transition: 'color 0.4s'
          }}
        >
          <path
            d="M11.5 2 L4.5 11 L9 11 L8 18 L15.5 8.5 L11 8.5 Z"
            fill="currentColor"
            stroke="currentColor"
            strokeWidth="0.6"
            strokeLinejoin="round"
          />
        </svg>
        <input
          value={name}
          onChange={(e) => onChange(id, { name: e.target.value })}
          onMouseDown={(e) => e.stopPropagation()}
          onFocus={(e) => e.target.select()}
          style={{
            background: 'transparent',
            border: 'none',
            outline: 'none',
            color: 'var(--ink-0)',
            fontSize: 16,
            fontWeight: 600,
            width: '100%',
            padding: '2px 0',
            borderBottom: '1px dashed transparent'
          }}
          onMouseEnter={(e) => e.target.style.borderBottomColor = 'var(--line-2)'}
          onMouseLeave={(e) => e.target.style.borderBottomColor = 'transparent'}
        />
      </div>
      {/* battery cells visual */}
      <div className="battery-cells" style={{
        position: 'relative',
        background: 'var(--bg-0)',
        border: '1px solid var(--line-2)',
        borderRadius: 6,
        padding: 4,
        height: 56,
        display: 'flex',
        gap: 3,
        marginBottom: 10,
        overflow: 'hidden'
      }}>
        {/* scanline effect */}
        {!empty && !overload && (
          <div style={{
            position: 'absolute',
            left: 0, right: 0,
            height: 2,
            background: `linear-gradient(90deg, transparent, ${fillColor}, transparent)`,
            opacity: 0.4,
            animation: 'scan 3s linear infinite',
            pointerEvents: 'none'
          }} />
        )}
        {Array.from({ length: cells }).map((_, i) => {
          const active = i < filledCells;
          return (
            <div key={i} style={{
              flex: 1,
              borderRadius: 2,
              background: active
                ? `linear-gradient(180deg, ${fillColor}, ${fillDim})`
                : 'var(--bg-2)',
              boxShadow: active ? `0 0 8px ${fillColor}, inset 0 0 6px rgba(255,255,255,0.2)` : 'none',
              transition: 'background 0.4s, box-shadow 0.4s',
              animation: overload && active ? 'pulse-glow 0.4s infinite' : 'none'
            }} />
          );
        })}
      </div>

      {/* readouts */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: '1fr 1fr',
        gap: 8,
        marginBottom: 4,
        fontFamily: 'JetBrains Mono, monospace'
      }}>
        <div>
          <div style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 2 }}>Capacity</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 2 }}>
            <span style={{ color: 'var(--ink-2)', fontSize: 11 }}>$</span>
            <input
              type="number"
              value={amount}
              onChange={(e) => onChange(id, { amount: parseFloat(e.target.value) || 0 })}
              onMouseDown={(e) => e.stopPropagation()}
              onFocus={(e) => e.target.select()}
              style={{
                background: 'transparent',
                border: 'none',
                outline: 'none',
                color: 'var(--ink-0)',
                fontSize: 18,
                fontWeight: 700,
                fontFamily: 'JetBrains Mono, monospace',
                width: '100%',
                padding: 0
              }}
            />
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 2 }}>Available</div>
          <div style={{
            fontSize: 18,
            fontWeight: 700,
            color: overload ? 'var(--red)' : empty ? 'var(--amber)' : fillColor,
            textShadow: `0 0 12px ${overload ? 'var(--red)' : fillColor}`,
            transition: 'color 0.3s'
          }}>
            ${remaining.toFixed(0)}
          </div>
        </div>
      </div>

      <div style={{
        fontFamily: 'JetBrains Mono, monospace',
        fontSize: 9,
        letterSpacing: '0.1em',
        color: 'var(--ink-3)',
        textTransform: 'uppercase',
        display: 'flex',
        justifyContent: 'space-between'
      }}>
        <span>Draw: ${draw.toFixed(0)}{periodSuffix}</span>
        <span>{Math.round(pct * 100)}%</span>
      </div>

      {/* output port — right edge */}
      <div
        data-port="source-out"
        data-source-id={id}
        onMouseDown={(e) => { e.stopPropagation(); onPortMouseDown(e, id); }}
        onTouchStart={(e) => { e.stopPropagation(); onPortMouseDown(e, id); }}
        style={{
          position: 'absolute',
          right: -14,
          top: '50%',
          transform: 'translateY(-50%)',
          width: 28,
          height: 28,
          borderRadius: '50%',
          background: 'var(--bg-1)',
          border: `2px solid ${pendingTarget ? 'var(--cyan)' : 'var(--line-2)'}`,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          cursor: 'crosshair',
          boxShadow: pendingTarget
            ? '0 0 16px rgba(76, 243, 255, 0.8)'
            : `0 0 8px ${overload ? 'var(--red-dim)' : 'var(--cyan-dim)'}`,
          transition: 'box-shadow 0.2s, border-color 0.2s'
        }}
      >
        <div style={{
          width: 10,
          height: 10,
          borderRadius: '50%',
          background: overload ? 'var(--red)' : empty ? 'var(--ink-3)' : fillColor,
          boxShadow: `0 0 12px ${overload ? 'var(--red)' : empty ? 'transparent' : fillColor}`,
          animation: !empty && !overload ? 'pulse-glow 1.2s infinite' : 'none'
        }} />
      </div>
    </div>
  );
};

window.Battery = Battery;
